﻿using EquipViewAppNet;
using SecsEquip;
using SecsEquip300;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EquipSecs300
{
    public delegate Dictionary<string, Dictionary<string, string>> OnRecipeItemEvent(string recipeName, out Dictionary<string, Dictionary<string, string>> recipeItemDecType);
    public class GEM_PPFormat : SecsEquipEx
    {
        public OnRecipeItemEvent FuGetRecipeItemHandler { get; set; }
        //public Func<string, Dictionary<string, Dictionary<string, string>>, Dictionary<string, Dictionary<string, string>>> FuGetRecipeItemHandler { get; set; }

        public Func<string, Dictionary<string, Dictionary<string, string>>> FuGetRecipeItemTypeHandler { get; set; }

        public Func<string, Dictionary<string, Dictionary<string, string>>, bool> FuSetRecipeItemHandler { get; set; }

        internal List<string> listRecipeItem = new List<string>();

        internal Dictionary<string, Dictionary<string, string>> recipeItem_DictTwoSend = new Dictionary<string, Dictionary<string, string>>();
        internal Dictionary<string, string> recipeItem_DictOneSend = new Dictionary<string, string>();
        internal Dictionary<string, Dictionary<string, string>> recipeItemType_DictTwoSend = new Dictionary<string, Dictionary<string, string>>();
        internal Dictionary<string, string> recipeItemType_DictOneSend = new Dictionary<string, string>();


        internal Dictionary<string, Dictionary<string, string>> recipeItem_DictTwoCur = new Dictionary<string, Dictionary<string, string>>();
        internal Dictionary<string, string> recipeItem_DictOneCur = new Dictionary<string, string>();
        internal Dictionary<string, Dictionary<string, string>> recipeItemType_DictTwoCur = new Dictionary<string, Dictionary<string, string>>();
        internal Dictionary<string, string> recipeItemType_DictOneCur = new Dictionary<string, string>();

        internal Dictionary<string, Dictionary<string, string>> recipeItem_DictTwoRec = new Dictionary<string, Dictionary<string, string>>();
        internal Dictionary<string, string> recipeItem_DictOneRec = new Dictionary<string, string>();
        internal Dictionary<string, Dictionary<string, string>> recipeItemType_DictTwoRec = new Dictionary<string, Dictionary<string, string>>();
        internal Dictionary<string, string> recipeItemType_DictOneRec = new Dictionary<string, string>();

        internal bool IsPPFormatAdded { get; set; }

        public GEM_PPFormat(CSecsEquip300 m_pSecs, SecsEquipHelper secsEquipHelper)
        {
            this.m_pSecs = m_pSecs;
            this.SecsEquipHelper = secsEquipHelper;
        }

        public override void UpdateData()
        {
            // 初始化应该放在SECS的初始化函数中
            m_pSecs.m_pOnPPFormatValueProc += OnPPFormatHandleEvent;
            m_pSecs.m_pOnPPFormatChangeProc += OnPPFormatChangeHandleEvent;
        }

        protected void PPFormatView_FormClosing(object sender, FormClosingEventArgs e)
        {
            //m_pSecs.m_pOnPPFormatValueProc = null;
        }
        /// <summary>
        /// 
        /// </summary>
        protected virtual List<string> ConvertDictTwoToList(Dictionary<string, Dictionary<string, string>> recipeItem_DictTwo)
        {
            List<string> listItem = new List<string>();
            foreach (var item in recipeItem_DictTwo)
            {
                foreach (var itemSub in item.Value)
                {
                    listItem.Add(itemSub.Value);
                }
            }
            return listItem;
        }
        /// <summary>
        /// 
        /// </summary>
        protected virtual Dictionary<string, Dictionary<string, string>> ConverListToDictTwo(List<string> recipeItemList, Dictionary<string, Dictionary<string, string>> recipeItem_DictTwoCur)
        {
            Dictionary<string, Dictionary<string, string>> recipeItem_DictTwo = new Dictionary<string, Dictionary<string, string>>();
            int n = 0;
            try
            {
                foreach (var item in recipeItem_DictTwoCur)
                {
                    recipeItem_DictTwo.Add(item.Key, new Dictionary<string, string>());
                    foreach (var itemSub in item.Value)
                    {
                        if (n >= recipeItemList.Count)//Dictionary中参数个数比List中多时添加自身
                        {
                            recipeItem_DictTwo[item.Key].Add(itemSub.Key, itemSub.Value);
                        }
                        else
                        {
                            recipeItem_DictTwo[item.Key].Add(itemSub.Key, recipeItemList[n]);
                        }

                        n++;
                    }
                }
                return recipeItem_DictTwo;
            }
            catch (Exception ex)
            {
                LogMsg(ex.Message, MsgSource_KE.EQ);
                return null;
            }

        }
        // Format上传
        public virtual void OnPPFormatHandleEvent(object sender, PPFormatEventArgs e)
        {
            #region 格式1 
            if (false)//格式1-用于单case上传下载(default:)。上传下载参数顺序要求一致。FormatPP.csv表格code为对应工单参数名
            {
                string ppid = "";
                if (e.nHandleType == PPFormatHandle.LoadPpid)
                {
                    ppid = e.ppid;
                    recipeItem_DictTwoSend = FuGetRecipeItemHandler?.Invoke(ppid, out recipeItemType_DictTwoSend);
                    if (recipeItem_DictTwoSend != null)
                    {
                        listRecipeItem = ConvertDictTwoToList(recipeItem_DictTwoSend);
                    }
                }
                // 逐一把数据返回        
                else if (e.nHandleType == PPFormatHandle.GetPpidValue)
                {
                    List<string> listValue = new List<string>();

                    switch (e.pCmdCode)
                    {
                        #region
                        //case "1":
                        //    {
                        //        foreach (var item in dictRecipeItem["InspParam"])
                        //        {
                        //            listValue.Add(item.Value);
                        //        }
                        //        break;
                        //    }
                        //case "2":
                        //    {
                        //        foreach (var item in dictRecipeItem["Light"])
                        //        {
                        //            listValue.Add(item.Value);
                        //        }
                        //        break;
                        //    }
                        //case "3":
                        //    {
                        //        foreach (var item in dictRecipeItem["WfInfo"])
                        //        {
                        //            listValue.Add(item.Value);
                        //        }
                        //        break;
                        //    }
                        #endregion
                        default:
                            {
                                int index = UtilitiesConvert.StringToInt32(e.pCmdCode) - 1;
                                if (listRecipeItem.Count > 0 && index < 21)
                                {
                                    listValue.Add(listRecipeItem[index]);
                                }
                            }
                            break;
                    }
                    e.listParamValue = listValue;
                }
            }
            #endregion

            #region 格式2
            else if (true)//格式2-（FormatPP.csv Code为基类参数数字编号）
            {
                string ppid = "";
                if (e.nHandleType == PPFormatHandle.LoadPpid)
                {
                    ppid = e.ppid;
                    recipeItem_DictTwoSend = FuGetRecipeItemHandler?.Invoke(ppid, out recipeItemType_DictTwoSend);
                    if (recipeItem_DictTwoSend != null)
                    {
                        listRecipeItem = ConvertDictTwoToList(recipeItem_DictTwoSend);
                    }
                }
                // 逐一把数据返回        
                else if (e.nHandleType == PPFormatHandle.GetPpidValue)
                {
                    List<string> listValue = new List<string>();
                    if (recipeItem_DictTwoSend != null)
                    {
                        try
                        {
                            switch (e.pCmdCode)
                            {
                                #region
                                case "1":
                                    {
                                        if (!recipeItem_DictTwoSend.ContainsKey("InspParam")) break;
                                        foreach (var item in recipeItem_DictTwoSend["InspParam"])
                                        {
                                            string strItem = $"name:{item.Key};value:{item.Value}";
                                            listValue.Add(strItem);
                                        }
                                        break;
                                    }
                                case "2":
                                    {
                                        if (!recipeItem_DictTwoSend.ContainsKey("Light")) break;
                                        foreach (var item in recipeItem_DictTwoSend["Light"])
                                        {
                                            string strItem = $"name:{item.Key};value:{item.Value}";
                                            listValue.Add(strItem);
                                        }
                                        break;
                                    }
                                case "3":
                                    {
                                        if (!recipeItem_DictTwoSend.ContainsKey("WfInfo")) break;
                                        foreach (var item in recipeItem_DictTwoSend["WfInfo"])
                                        {
                                            string strItem = $"name:{item.Key};value:{item.Value}";
                                            listValue.Add(strItem);
                                        }
                                        break;
                                    }
                                case "4":
                                    {
                                        if (!recipeItem_DictTwoSend.ContainsKey("AVIParam")) break;
                                        foreach (var item in recipeItem_DictTwoSend["AVIParam"])
                                        {
                                            string strItem = $"name:{item.Key};value:{item.Value}";
                                            listValue.Add(strItem);
                                        }
                                        break;
                                    }
                                #endregion
                                default:
                                    {

                                    }
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogMsg(ex.Message, MsgSource_KE.EQ);
                        }

                    }

                    e.listParamValue = listValue;
                }
            }
            #endregion

        }

        // Format 下载
        protected string ppid = "";
        public virtual void OnPPFormatChangeHandleEvent(object sender, PPFormatEventArgs e)
        {
            if (false)//格式1-下载工单使用
            {
                // 新建或者打开已有的一个recipe        
                if (e.nHandleType == PPFormatHandle.SetPpidVlaueBegin)
                {
                    ppid = e.ppid;
                    recipeItem_DictTwoCur = FuGetRecipeItemHandler?.Invoke(ppid, out recipeItemType_DictTwoCur);
                    listRecipeItem.Clear();
                }

                // 向打开的recipe写入数据          
                else if (e.nHandleType == PPFormatHandle.SetPpidVlaue)
                {
                    List<string> listValue = e.listParamValue;
                    int n = 0;
                    switch (e.pCmdCode)
                    {
                        #region
                        //case "1":
                        //    {
                        //        foreach (var item in dictRecipeItem["InspParam"].Keys)
                        //        {
                        //            dictRecipeItem["InspParam"][item] = listValue[n];
                        //        }
                        //    }
                        //    break;
                        //case "2":
                        //    {
                        //        foreach (var item in dictRecipeItem["Light"].Keys)
                        //        {
                        //            dictRecipeItem["Light"][item] = listValue[n];
                        //        }
                        //    }
                        //    break;
                        //case "3":
                        //    {
                        //        foreach (var item in dictRecipeItem["WfInfo"].Keys)
                        //        {
                        //            dictRecipeItem["WfInfo"][item] = listValue[n];
                        //        }
                        //    }
                        //    break;
                        #endregion
                        default:
                            {
                                int index = UtilitiesConvert.StringToInt32(e.pCmdCode) - 1;
                                listRecipeItem.Add(listValue[0]);
                            }
                            break;
                    }
                }

                // 保存recipe      
                else if (e.nHandleType == PPFormatHandle.SetPpidVlaueFinsh)
                {
                    recipeItem_DictTwoRec = ConverListToDictTwo(listRecipeItem, recipeItem_DictTwoCur);
                    FuSetRecipeItemHandler?.Invoke(ppid, recipeItem_DictTwoRec);
                }
            }
            else if (true)
            {
                // 新建或者打开已有的一个recipe        
                if (e.nHandleType == PPFormatHandle.SetPpidVlaueBegin)
                {
                    ppid = e.ppid;
                    recipeItem_DictTwoCur = FuGetRecipeItemHandler?.Invoke(ppid, out recipeItemType_DictTwoCur);
                    listRecipeItem.Clear();
                }

                // 向打开的recipe写入数据          
                else if (e.nHandleType == PPFormatHandle.SetPpidVlaue)
                {
                    List<string> listValue = e.listParamValue;
                    int n = 0;
                    if (recipeItem_DictTwoSend != null)
                    {
                        try
                        {
                            switch (e.pCmdCode)
                            {

                                default:
                                    {

                                    }
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogMsg(ex.Message, MsgSource_KE.EQ);
                        }

                    }

                }

                // 保存recipe      
                else if (e.nHandleType == PPFormatHandle.SetPpidVlaueFinsh)
                {
                    recipeItem_DictTwoRec = ConverListToDictTwo(listRecipeItem, recipeItem_DictTwoCur);
                    FuSetRecipeItemHandler?.Invoke(ppid, recipeItem_DictTwoRec);
                }
            }
        }

        // 参数的类型
        // listParament参数的列表
        protected string RecipeJoin(List<string> listParament, string pDataFormat)
        {
            string pTmp;
            List<string> listSML = new List<string>();
            listSML.Add("L");

            for (int i = 0; i < listParament.Count; i++)
            {
                pTmp = CListOperate.listJoin(pDataFormat, listParament[i]);
                listSML.Add(pTmp);
            }

            pTmp = CListOperate.listJoin(listSML);
            return pTmp;
        }

        internal virtual bool PPFormatAdd(Dictionary<string, string> recipeItem_Dict, Dictionary<string, string> recipeItem_DictType)
        {
            bool isAllSucc = true;
            if (recipeItem_Dict == null || recipeItem_DictType == null || recipeItem_Dict.Count == 0 || recipeItem_DictType.Count == 0)
            {
                return false;
            }
            if (recipeItem_Dict.Count != recipeItem_DictType.Count)
            {
                return false;
            }
            foreach (var item in recipeItem_Dict)
            {
                try
                {
                    RcResult rc = m_pSecs.PPFormatAdd(item.Key, item.Value, ConvertType(recipeItem_DictType[item.Key]));
                    if (rc != 0)
                    {
                        LogMsg($"ERR: PPFormatAdd 添加失败 -> PP Cmd Code:{item.Key}, PP Name: {item.Value}");
                        isAllSucc = false;
                    }
                }
                catch (Exception ex)
                {
                    LogMsg($"ERR: PPFormatAdd 添加失败 -> PP Cmd Code:{item.Key}, PP Name: {item.Value} -> {ex.Message}");
                    isAllSucc = false;
                }
            }
            IsPPFormatAdded = true;
            return isAllSucc;
        }

        internal string ConvertType(string sourceType)
        {
            string retType = "A";
            switch (sourceType)
            {
                case "Boolean":
                    {
                        retType = "TF";
                    }
                    break;
                case "Int32":
                    {
                        retType = "I8";
                    }
                    break;
                case "Int16":
                    {
                        retType = "I4";
                    }
                    break;
                case "UInt16":
                    {
                        retType = "U2";
                    }
                    break;
                case "Double":
                    {
                        retType = "F8";
                    }
                    break;
                case "String":
                    {
                        retType = "A";
                    }
                    break;
                default:
                    break;
            }
            return retType;
        }

        // 发送FromatPP
        public void SendPP(string ppID)
        {
            m_pSecs.PPFormatSend(ppID);
        }

        // 请求FromatPP
        public void RequstPP(string ppID)
        {
            m_pSecs.PPFormatRequest(ppID);
        }

        internal void SaveFormatPPToCsv(string name, Dictionary<string, string> recipeItem_Dict, Dictionary<string, string> recipeItem_DictType)
        {
            if (recipeItem_Dict == null|| recipeItem_DictType==null)
            {
                return;
            }
            if (recipeItem_Dict.Count!= recipeItem_DictType.Count)
            {
                return;
            }
            string filePath = $"D:\\PPFormatBody\\{name}";
            string fileHeader = $"Name,Value,Type";
            CsvHelper recipeItemCsv = new CsvHelper(filePath, fileHeader);
            try
            {
                foreach (var item in recipeItem_Dict)
                {
                    string str = $"{item.Key},{item.Value},{recipeItem_DictType[item.Key]}";
                    recipeItemCsv.Write(str);
                    recipeItemCsv.Record();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            
        }
    }
}
